package com.example.bootdemo.controller;

import com.example.bootdemo.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;

@Slf4j
@RestController
@RequestMapping(value = "countDownLatch", produces = MediaType.APPLICATION_JSON_VALUE)
public class CountDownLatchController {
    final CountDownLatch countDownLatch = new CountDownLatch(5);

    public static int count1 = 0;

    @RequestMapping(value = "countDown", method = RequestMethod.GET)
    public  R countDown() throws Exception {

                try {
                    test(count1++);
                } catch (Exception e) {
                    log.error("exception", e);
                } finally {
                    countDownLatch.countDown();
                }

        countDownLatch.await();
        log.info("finish");
           return R.ok(String.valueOf(count1));
    }

    private static void test(int threadNum) throws Exception {
        Thread.sleep(100);
        log.info("{}", threadNum);
        Thread.sleep(100);
    }
}
